/*
 * @Descripttion:
 * @Author: jhw
 * @Date: 2023-04-28 21:57:02
 * @LastEditors: jhw
 * @LastEditTime: 2024-06-19 11:49:42
 */
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import autoprefixer from 'autoprefixer'; // https://vitejs.dev/config/
import WindiCSS from 'vite-plugin-windicss';
import path, { resolve } from 'path';
import legacy from '@vitejs/plugin-legacy';
import vueJsx from '@vitejs/plugin-vue-jsx';
import svgPlugin from 'vite-plugin-svg';
import Inspect from 'vite-plugin-inspect'; // 源代码分析
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import chunkFileNames from './build/chunkFileNames';

const ROOT = process.cwd();
const autoprefixerPlugin = autoprefixer();

export default defineConfig(({ command, mode }) => {
  console.log(command, mode, '参数');
  const env = loadEnv(mode, ROOT);
  const { VITE_PORT, VITE_BUILD_NAME } = env;
  console.log(ROOT, 'VITE_BUILD_NAME');

  return {
    plugins: [
      vue(),
      vueJsx(),
      WindiCSS(),
      Inspect(),
      legacy({
        targets: ['cover 99.5%'],
      }),
      svgPlugin(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(ROOT, 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false), // 或者 true，根据你的需求
    },
    build: {
      cssCodeSplit: false,
      outDir: path.resolve(ROOT, VITE_BUILD_NAME),
      chunkSizeWarningLimit: 1024,

      emptyOutDir: true,
      // sourcemap: true,
      rollupOptions: {
        plugins: [],
        output: {
          chunkFileNames,
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: ['vue'],
            elementPlus: ['element-plus'],
            // windicss: ['windicss'], // 名称不对，不会被拆分
            echarts: ['echarts'],
          },
        },
      },
    },
    css: {
      postcss: {
        plugins: [autoprefixerPlugin as any],
      },
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@/styles/variables.scss";`,
        },
      },
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
      extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      port: Number(VITE_PORT) || 8080,
      open: true,
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:8888', // 贾浩旺
          changeOrigin: true,
          rewrite(paths) {
            return paths.replace('/api', '');
          },
        },
      },
    },
    // 依赖预构建
    optimizeDeps: {
      entries: ['**/*.vue', '**/*.ts'],
      include: ['core-js', 'vue'],
    },
  };
});
